var businessBillInfo=unescape(T.p("businessBillInfo"));
var businessBillInfo = JSON.parse(businessBillInfo);
console.log("businessBillInfo:");
console.log(businessBillInfo);
console.log("customerInfoId:");
console.log(businessBillInfo.customerInfoId);
var businessBill=unescape(T.p("businessBill"));
var businessBill = JSON.parse(businessBill);
console.log("businessBill:");
console.log(businessBill);

$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'erp/businessbill/list',
        datatype: "json",
        colModel: [			
			{ label: 'businessBillId', name: 'businessBillId', index: 'business_bill_id', width: 50, key: true },
			{ label: '订单编号', name: 'billCode', index: 'bill_code', width: 80 }, 			
			{ label: '订单日期', name: 'billDate', index: 'bill_date', width: 80 }, 			
			{ label: '客户编码', name: 'customerCode', index: 'customer_code', width: 80 }, 			
			{ label: '送货地点', name: 'deliveryAddress', index: 'delivery_address', width: 80 }, 			
			{ label: '送货部门', name: 'deliveryPart', index: 'delivery_part', width: 80 }, 			
			{ label: '客户PO', name: 'customerPo', index: 'customer_po', width: 80 }, 			
			{ label: '付款期', name: 'paymentMethod', index: 'payment_method', width: 80 }, 			
			{ label: '货币', name: 'currencyType', index: 'currency_type', width: 80 }, 			
			{ label: '客方货号', name: 'customerGoodsCode', index: 'customer_goods_code', width: 80 }, 			
			{ label: '盒式', name: 'boxCode', index: 'box_code', width: 80 }, 			
			{ label: '啤模编号', name: 'pimoCode', index: 'pimo_code', width: 80 }, 			
			{ label: '纸质', name: 'paperCode', index: 'paper_code', width: 80 }, 			
			{ label: '调整纸质', name: 'changePaperCode', index: 'change_paper_code', width: 80 }, 			
			{ label: '长', name: 'paperLong', index: 'paper_long', width: 80 }, 			
			{ label: '宽', name: 'paperWide', index: 'paper_wide', width: 80 }, 			
			{ label: '高', name: 'paperHeight', index: 'paper_height', width: 80 }, 			
			{ label: '调长', name: 'changeLong', index: 'change_long', width: 80 }, 			
			{ label: '调宽', name: 'changeWide', index: 'change_wide', width: 80 }, 			
			{ label: '调高', name: 'changeHeight', index: 'change_height', width: 80 }, 			
			{ label: '单位', name: 'paperUnite', index: 'paper_unite', width: 80 }, 			
			{ label: '钉口', name: 'dingKou', index: 'ding_kou', width: 80 }, 			
			{ label: '送货时间', name: 'deliberyTime', index: 'delibery_time', width: 80 }, 			
			{ label: '配件', name: 'peiJian', index: 'pei_jian', width: 80 }, 			
			{ label: '数量', name: 'totalNum', index: 'total_num', width: 80 }, 			
			{ label: '备品数', name: 'bkNum', index: 'bk_num', width: 80 }, 			
			{ label: '包装数', name: 'packageNum', index: 'package_num', width: 80 }, 			
			{ label: '单价', name: 'onePrice', index: 'one_price', width: 80 }, 			
			{ label: '金额', name: 'totalPrice', index: 'total_price', width: 80 }, 			
			{ label: '单重', name: 'oneWeight', index: 'one_weight', width: 80 }, 			
			{ label: '面积', name: 'totalArea', index: 'total_area', width: 80 }, 			
			{ label: '生产备注', name: 'productRemark', index: 'product_remark', width: 80 }, 			
			{ label: '供应商', name: 'supplierCode', index: 'supplier_code', width: 80 }, 			
			{ label: '备注', name: 'remark', index: 'remark', width: 80 }, 			
			{ label: '特殊规格', name: 'specialRemark', index: 'special_remark', width: 80 }, 			
			{ label: '备注1', name: 'remark1', index: 'remark1', width: 80 }, 			
			{ label: '备注2', name: 'remark2', index: 'remark2', width: 80 }, 			
			{ label: '料一', name: 'useOne', index: 'use_one', width: 80 }, 			
			{ label: '料二', name: 'useTwo', index: 'use_two', width: 80 }, 			
			{ label: '插接口', name: 'insertInterface', index: 'insert_interface', width: 80 }, 			
			{ label: '厚度', name: 'thickSize', index: 'thick_size', width: 80 }, 			
			{ label: '有效标识（1：有效0：无效）', name: 'status', index: 'status', width: 80 }			
        ],
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        shrinkToFit:false, //给jqgrid横向添加滚动条 
    	autoScroll: true,  //给jqgrid横向添加滚动条
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	//$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        	//------------------------给jqgrid横向添加滚动条-------------------------------------------------------------
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "scroll" }); 

        }
    });
});

var vm = new Vue({
	el:'#rrapp',
	data:{
		showList: true,
		title: null,
		businessBill: {},
	    billDateStr: new Date(),
	    customerVO: {},
	    customerCode: '',
	    paymentMethodOptions: [],
	    paymentMethod: '',
	    currencyTypeOptions: [],
        currencyType: '',
        customerGoodsCode: '',
        customerList: [],
        businessbills: [],
        businessbillVO: {},
        boxCode: '',
        boxCodeVO: {},
        boxCodeList: [],
        pimoCodeList: [],
        pimoCode: '',
        paperCodeList: [],
        paperCode: '',
        paperCodeVO: {},
        changePaperCode: '',
        unitTypeOptions: [],
		unitType: '',
		peiJian: false,
		priceFormula: '',
		weightFormula: '',
		areaFormula: '',
		baojia: '',
		jizhong: '',
		dingkou: '',
		price: '',
		totalPrice: '',
		weight: '',
		totalWeight: '',
		area: '',
		paperLong: '',
		paperWide: '',
		paperHeight: '',
		changeLong: '',
		changeWide: '',
		changeHeight: '',
		customerPriceList: [],
		
	},
	created(){
		if(businessBillInfo){
			this.showList = false;
			this.title = "新增";
			this.businessBill = businessBillInfo;
			this.billDateStr = new Date(businessBillInfo.billDate);
			this.customerCode = businessBillInfo.customerCode;
			this.businessBill.deliveryAddress = businessBillInfo.deliveryAddress;
			this.businessBill.deliveryPart = businessBillInfo.deliveryPart;
			this.paymentMethod = businessBillInfo.paymentMethod;
			this.currencyType = businessBillInfo.currencyType;
			
		}
		if(businessBill){
			var businessBillId=businessBill.businessBillId;
			this.getInfo(businessBillId);
	  }
	},
	methods: {
		query: function () {
			vm.reload();
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.businessBill = {};
		},
		update: function (event) {
			var businessBillId = getSelectedRow();
			if(businessBillId == null){
				return ;
			}
			vm.showList = false;
            vm.title = "修改";
            vm.getInfo(businessBillId);
		},
		saveOrUpdate: function (event) {
			var url = vm.businessBill.businessBillId == null ? "erp/businessbill/save" : "erp/businessbill/update";
			//构造参数
			console.log(vm.businessBill);
			vm.businessBill.billDateStr=getFormatDate(this.billDateStr);
			for(var i=0;i<this.customerList.length;i++){
				if(this.customerCode==this.customerList[i].customerCode){
					this.customerVO=this.customerList[i];
					break;
				}
			}
			vm.businessBill.customerCode=this.customerVO.customerCode;
			vm.businessBill.deliveryAddress=this.customerVO.deliveryAddress;
			if(this.customerVO.deliveryPart){
				vm.businessBill.deliveryPart=this.customerVO.deliveryPart;
			}
			vm.businessBill.paymentMethod=this.paymentMethod;
			vm.businessBill.currencyType=this.currencyType;
			vm.businessBill.customerGoodsCode=this.customerGoodsCode;
			vm.businessBill.boxCode=this.boxCode;
			vm.businessBill.pimoCode=this.pimoCode;
			vm.businessBill.paperCode=this.paperCode;
			vm.businessBill.changePaperCode=this.changePaperCode;
			vm.businessBill.paperLong=this.paperLong;
			vm.businessBill.paperWide=this.paperWide;
			vm.businessBill.paperHeight=this.paperHeight;
			vm.businessBill.changeLong=this.changeLong;
			vm.businessBill.changeWide=this.changeWide;
			vm.businessBill.changeHeight=this.changeHeight;
			vm.businessBill.paperUnite=this.unitType;
			if(this.peiJian){
				vm.businessBill.peiJian=1;
			}else{
				vm.businessBill.peiJian=0;
			}
			vm.businessBill.onePrice=this.price;
			vm.businessBill.totalPrice=this.totalPrice;
			vm.businessBill.oneWeight=this.weight;
			vm.businessBill.totalArea=this.area;
			
			if(businessBillInfo){
				vm.businessBill.businessBillInfoId=businessBillInfo.businessBillInfoId;
			}
			console.log(vm.businessBill);
			$.ajax({
				type: "POST",
			    url: baseURL + url,
                contentType: "application/json",
			    data: JSON.stringify(vm.businessBill),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
							//vm.callbackBT();
							window.location.href="../erp/modules/erp/businessbillinfo.html?businessBillInfo="+escape(JSON.stringify(businessBillInfo));
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		del: function (event) {
			var businessBillIds = getSelectedRows();
			if(businessBillIds == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "erp/businessbill/delete",
                    contentType: "application/json",
				    data: JSON.stringify(businessBillIds),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(businessBillId){
			$.get(baseURL + "erp/businessbill/info/"+businessBillId, function(r){
                vm.businessBill = r.businessBill;
                vm.billDateStr = new Date(r.businessBill.billDate);
                vm.customerCode = r.businessBill.customerCode;
                if(businessBillInfo && businessBillInfo.deliveryPart){
                	vm.businessBill.deliveryPart = businessBillInfo.deliveryPart;
                }
                vm.paymentMethod = r.businessBill.paymentMethod;
                vm.currencyType = r.businessBill.currencyType;
                vm.customerGoodsCode = r.businessBill.customerGoodsCode;
                
                vm.boxCode=r.businessBill.boxCode;
    			vm.pimoCode=r.businessBill.pimoCode;
    			vm.paperCode=r.businessBill.paperCode;
    			vm.changePaperCode=r.businessBill.changePaperCode;
    			vm.paperLong=r.businessBill.paperLong;
    			vm.paperWide=r.businessBill.paperWide;
    			vm.paperHeight=r.businessBill.paperHeight;
    			vm.changeLong=r.businessBill.changeLong;
    			vm.changeWide=r.businessBill.changeWide;
    			vm.changeHeight=r.businessBill.changeHeight;
    			vm.unitType=r.businessBill.paperUnite;
    			if(r.businessBill.peiJian==1){
    				vm.peiJian=true;
    			}else{
    				vm.peiJian=false;
    			}
    			vm.price=r.businessBill.onePrice;
    			vm.totalPrice=r.businessBill.totalPrice;
    			vm.weight=r.businessBill.oneWeight;
    			vm.area=r.businessBill.totalArea;
            });
		},
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{ 
                page:page
            }).trigger("reloadGrid");
		},
		callbackBT: function(){
			window.location.href="businessbillinfo.html?businessBillInfo="+escape(JSON.stringify(businessBillInfo));
		},
		querySearch(queryString, cb) {
//			 var restaurants = [{value:"10",name:"a"},{value:"20",name:"b"}];
//		        var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
//		        // 调用 callback 返回建议列表的数据
//		        cb(results);
			$.get(baseURL + "erp/businessbill/list", 
			{
	            page:{"currPage":1,"limit":10}
		        },
		        function(r){
	                if(r.code==0){
	                	vm.businessbills=r.page.list;
	                	//vm.businessbills=[{value:"10",name:"a"},{value:"20",name:"b"}];
	        	        var businessbills = vm.businessbills;
	        	        console.log(businessbills);
	        	        for(var i=0;i<businessbills.length;i++){
	        	        	businessbills[i].value=businessbills[i].customerGoodsCode;
	        	        }
	        	        var results = queryString ? businessbills.filter(vm.createFilter(queryString)) : businessbills;
	        	        //var results = vm.createFilter(queryString);
	        	        // 调用 callback 返回建议列表的数据
	        	        cb(results);
	                }
	            }
	        );
			
		 },
		 createFilter(queryString) {
		    return (businessbill) => {
		      return (businessbill.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
		    };
		 },
		 handleSelect(item) {
			 console.log(item);
		 },
		 handleIconClick(ev) {
			 console.log(ev);
		 },
		 getCustomerList: function(){
			$.get(baseURL + "erp/customerinfo/list", 
				{
			        page:{"currPage":1,"limit":10}
			    },
			    function(r){
			        if(r.code==0){
			        	vm.customerList=r.page.list;
			        }
			    }
			);
		},
		changeCustomer:function(){
			for(var i=0;i<this.customerList.length;i++){
				if(this.customerCode==this.customerList[i].customerCode){
					this.customerVO=this.customerList[i];
					break;
				}
			}
			this.getCustomerPrice(this.customerVO.customerInfoId);
		},
		getCustomerPrice:function(customerInfoId){
			$.get(baseURL + "erp/customerprice/priceinfo/"+customerInfoId, 
			        function(r){
		                if(r.code==0){
		                	vm.customerPriceList=r.customerPriceList;
		                	if(vm.paperCode!=""){
		                		for(var i=0;i<vm.customerPriceList.length;i++){
			                		if(vm.customerPriceList[i].paperCode==vm.paperCode){
			                			vm.baojia=vm.customerPriceList[i].newPrice;
			                			break;
			                		}
			                	}
		                	}
		                }
		            }
		        );
		},
		changePaperCodeEv:function(){
			for(var j=0;j<vm.paperCodeList.length;j++){
				if(vm.paperCode==vm.paperCodeList[j].paperCode){
					vm.paperCodeVO=vm.paperCodeList[j];
					vm.jizhong=vm.paperCodeList[j].paperWeight;
					vm.businessBill.insertInterface=vm.paperCodeList[j].insertInterface;
					vm.businessBill.thickSize=vm.paperCodeList[j].thickSize;
					break;
				}
			}
			if(vm.paperCode!="" && vm.customerPriceList.length>0){
        		for(var i=0;i<vm.customerPriceList.length;i++){
            		if(vm.customerPriceList[i].paperCode==vm.paperCode){
            			vm.baojia=vm.customerPriceList[i].newPrice;
            			break;
            		}
            	}
        	}
		},
		getPayMethodList: function(){
			$.get(baseURL + "erp/baseparam/findInfoByCode", 
					{
						"paramCode":"PAYMENT_METHOD"
					},
			        function(r){
		                if(r.code==0){
		                	vm.paymentMethodOptions=r.list;
		                }
		            }
		        );
		},
		getCurrencyTypeList: function(){
			$.get(baseURL + "erp/baseparam/findInfoByCode", 
					{
						"paramCode":"CURRENCY_TYPE"
					},
			        function(r){
		                if(r.code==0){
		                	vm.currencyTypeOptions=r.list;
		                }
		            }
		        );
		},
		clearAllData: function(){
			vm.businessBill={};
			vm.billDateStr= new Date();
		    vm.customerVO= {};
		    vm.customerCode= '';
		    vm.paymentMethod= '';
	        vm.currencyType= '';
	        vm.customerGoodsCode= '';
	        vm.businessbillVO= {};
		},
		queryBoxInfo() {
			$.get(baseURL + "erp/boxinfo/list", 
			{
	            page:{"currPage":1,"limit":10}
		        },
		        function(r){
	                if(r.code==0){
	                	vm.boxCodeList=r.page.list;
	                }
	            }
	        );
			
		 },
		 queryPimoInfo() {
				$.get(baseURL + "erp/pimoinfo/list", 
				{
		            page:{"currPage":1,"limit":10}
			        },
			        function(r){
		                if(r.code==0){
		                	vm.pimoCodeList=r.page.list;
		                	console.log(vm.pimoCodeList);
		                }
		            }
		        );
				
		 },
		 queryPaperInfo() {
				$.get(baseURL + "erp/paperinfo/alllist", 
				{},
			        function(r){
		                if(r.code==0){
		                	vm.paperCodeList=r.list;
		                }
		            }
		        );
				
		 },
		 getUnitInfoList: function(){
				$.get(baseURL + "erp/baseparam/findInfoByCode", 
						{
							"paramCode":"UNIT_TYPE"
						},
				        function(r){
			                if(r.code==0){
			                	vm.unitTypeOptions=r.list;
			                }
			            }
			        );
		 },
		 changeUnit:function(){
			for(var i=0;i<this.unitTypeOptions.length;i++){
				if(this.unitType==this.unitTypeOptions[i].paramValue){
					this.businessBill.uniteValue=this.unitTypeOptions[i].attr1;
					break;
				}
			}
		},
		changeBoxInfo:function(){
			for(var i=0;i<this.boxCodeList.length;i++){
				if(this.boxCode==this.boxCodeList[i].boxCode){
					this.boxCodeVO=this.boxCodeList[i];
					this.priceFormula=this.boxCodeVO.priceFormula;
					this.weightFormula=this.boxCodeVO.weightFormula;
					this.areaFormula=this.boxCodeVO.areaFormula;
					break;
				}
			}
		},
		calculateTotalPrice:function(){
			this.totalPrice=this.price*this.businessBill.totalNum;
			console.log("金额："+this.totalPrice);
		},
		calculateFormula:function(){
			var long=Number(isNaN(this.paperLong)?0:this.paperLong)+Number(isNaN(this.changeLong)?0:this.changeLong);
			var wide=Number(isNaN(this.paperWide)?0:this.paperWide)+Number(isNaN(this.changeWide)?0:this.changeWide);
			var height=Number(isNaN(this.paperHeight)?0:this.paperHeight)+Number(isNaN(this.changeHeight)?0:this.changeHeight);
			console.log("long:"+long+" wide:"+wide+" height:"+height);
			//计算单价
			var priceC=this.priceFormula.replace(new RegExp("长",'g'),long);
			priceC=priceC.replace(new RegExp("宽",'g'),wide);
			priceC=priceC.replace(new RegExp("高",'g'),height);
			priceC=priceC.replace(new RegExp("单价",'g'),this.baojia);
			console.log("计算单价="+priceC);
			this.price=eval(priceC);
			console.log("price:"+this.price);
			//计算单重
			var weightC=this.weightFormula.replace(new RegExp("长",'g'),long);
			weightC=weightC.replace(new RegExp("宽",'g'),wide);
			weightC=weightC.replace(new RegExp("高",'g'),height);
			weightC=weightC.replace(new RegExp("基重",'g'),this.jizhong);
			console.log("计算单重="+weightC);
			this.weight=eval(weightC);
			console.log("weight:"+this.weight);
			//计算单面积
			var areaC=this.areaFormula.replace(new RegExp("长",'g'),long);
			areaC=areaC.replace(new RegExp("宽",'g'),wide);
			areaC=areaC.replace(new RegExp("高",'g'),height);
			areaC=areaC.replace(new RegExp("钉口",'g'),this.dingkou);
			console.log("计算单重="+areaC);
			this.area=eval(areaC);
			console.log("area:"+this.area);
			
		}
	},
	mounted() {
	      this.getCustomerList();
		  this.getPayMethodList();
		  this.getCurrencyTypeList();
	      this.queryBoxInfo();
	      this.queryPimoInfo();
	      this.queryPaperInfo();
	      this.getUnitInfoList();
	      this.getCustomerPrice(businessBillInfo.customerInfoId);
	}
});

//日期格式化
function getFormatDate(date) {
    //var date = new Date();
	if(date==undefined || date==null || date==""){
		return "";
	}
    var seperator1 = "-";
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = year + seperator1 + month + seperator1 + strDate;
    return currentdate;
}
